/**
 * 转换并上传工具实现
 */

import { excelGenerator } from '../../excel/generator.js';
import { minioUploader } from '../../minio/uploader.js';
import { basename } from 'path';

export interface ConvertAndUploadParams {
  name: string;
  fields: string[];
  data: Array<string[]>;
}

export class TestCaseSessionTool {
  async create(args: { name: string; fields: string[] }) {
    const { name, fields } = args;

    // 校验 name 是否存在
    if (!name) {
      throw new Error('Name is required for creating Excel session');
    }

    // 校验 fields 是否存在且为非空数组
    if (!fields || !Array.isArray(fields) || fields.length === 0) {
      throw new Error('Fields array is required and must not be empty');
    }

    // 让底层的异常直接抛出，框架会自动设置 isError: true
    const sessionId = await excelGenerator.createExcelSession(name, fields);
    return { success: true, data: { sessionId } };
  }
  
  async append(args: { sessionId: string; data: Array<string[]> }) {
    const { sessionId, data } = args;
    
    if (!sessionId) {
      throw new Error('Session ID is required for appending data');
    }
    
    if (!data || !Array.isArray(data) || data.length === 0) {
      throw new Error('Data array is required and must not be empty');
    }
    
    // 让底层的异常直接抛出，框架会自动设置 isError: true
    await excelGenerator.appendToExcelSession(sessionId, data);
    return { success: true, message: `Appended ${data.length} rows.` };
  }
  
  async finalize(args: { sessionId: string }) {
    const { sessionId } = args;
    
    if (!sessionId) {
      throw new Error('Session ID is required for finalizing session');
    }
    
    // 让底层的异常直接抛出，框架会自动设置 isError: true
    const filePath = await excelGenerator.finalizeExcelSession(sessionId);
    const objectName = `test-cases/${basename(filePath)}`;
    const result = await minioUploader.uploadFile({ filePath, objectName });
    
    // 如果上传失败，抛出异常让大模型明确知道失败了
    if (!result.success) {
      throw new Error(`Upload failed: ${result.message}`);
    }
    
    return {
      success: true,
      message: 'Successfully uploaded test cases to Minio',
      data: {
        objectName: result.objectName,
        presignedUrl: result.presignedUrl,
      },
    };
  }
}
